package com.xiuxia.bopicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiuxia.bopicturebackend.constant.UserConstant;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.exception.ThrowUtils;
import com.xiuxia.bopicturebackend.manager.auth.StpKit;
import com.xiuxia.bopicturebackend.mapper.UserMapper;
import com.xiuxia.bopicturebackend.model.dto.user.UserQueryRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.user.UserRegisterRequestDTO;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.enums.UserRoleEnum;
import com.xiuxia.bopicturebackend.model.vo.user.UserLoginVO;
import com.xiuxia.bopicturebackend.model.vo.user.UserVO;
import com.xiuxia.bopicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 17732
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-04-19 14:26:15
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    @Transactional
    public long userRegister(UserRegisterRequestDTO userRegisterRequestDTO) {
        // 1.校验参数是否为空
        ThrowUtils.throwIf(
                StrUtil.hasBlank(userRegisterRequestDTO.getUserAccount(),
                        userRegisterRequestDTO.getUserPassword(),
                        userRegisterRequestDTO.getCheckPassword()
                ), new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空"));
        //2.校验参数长度是否超出范围
        ThrowUtils.throwIf(userRegisterRequestDTO.getUserAccount().length() < 4, new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号长度过短"));
        ThrowUtils.throwIf(userRegisterRequestDTO.getUserPassword().length() < 8 || userRegisterRequestDTO.getCheckPassword().length() < 8, new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码长度过短"));
        ThrowUtils.throwIf(!userRegisterRequestDTO.getUserPassword().equals(userRegisterRequestDTO.getCheckPassword()), new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致"));
        //3.密码加密
        String encryptPassword = getEncryptPassword(userRegisterRequestDTO.getUserPassword());
        long count = this.count(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userRegisterRequestDTO.getUserAccount()));
        ThrowUtils.throwIf(count > 0, new BusinessException(ErrorCode.SYSTEM_ERROR, "账号已存在"));
        //4.保存到数据库
        User user = new User();
        user.setUserAccount(userRegisterRequestDTO.getUserAccount());
        user.setUserPassword(encryptPassword);
        user.setUserName("初始名称");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败"));
        return user.getId();
    }

    @Override
    public UserLoginVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验参数是否为空
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空"));
        ThrowUtils.throwIf(userAccount.length() < 4, new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号错误"));
        ThrowUtils.throwIf(userPassword.length() < 8, new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码错误"));
        // 2.对密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 3.查询用户是否存在
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, encryptPassword));
        ThrowUtils.throwIf(user == null, new BusinessException(ErrorCode.SYSTEM_ERROR, "账号或密码错误"));
        // 4.保存用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        // 5.保存用户登录态到sa-token
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE, user);
        return this.getUserLoginVO(user);
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        final String SALT = "Freedom";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null, new BusinessException(ErrorCode.NOT_LOGIN_ERROR));
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(currentUser == null, new BusinessException(ErrorCode.NOT_LOGIN_ERROR));
        return currentUser;
    }

    @Override
    public UserLoginVO getUserLoginVO(User user) {
        if (user == null) {
            return null;
        }
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtil.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(userObj == null, new BusinessException(ErrorCode.OPERATION_ERROR, "未登录"));
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            new ArrayList<User>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequestDTO userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole().equals(UserRoleEnum.ADMIN.getValue());
    }


}




